<template>
  <el-container>
    <el-main>
      <el-form ref="productForm" :model="form" label-width="90px">
        <div style="display: flex">
          <div>
            <el-form-item label="团购名称" prop="name" style="width: 300px"
                          :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }">
              <el-input v-model="form.name"/>
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle" style="width: 570px">
              <el-input v-model="form.subTitle"/>
            </el-form-item>
            <el-form-item label="起止日期" prop="endDate"
                          :rules="{ required: true, message: '请选择起止日期', trigger: 'blur' }">
              <el-date-picker
                v-model="form.endDate"
                type="datetimerange"
                style="width: 480px"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>


            <el-form-item label="分销策略" style="width: 300px">
              <el-select v-model="form.distributionId" style="width: 100%" clearable filterable :filter-method="queryDistribution" placeholder="请选择">
                <el-option
                  v-for="item in disOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

          </div>
          <div>
            <el-form-item label="商品主图">
              <single-upload style="width: 145px" v-model="form.thumbnail"/>
            </el-form-item>
          </div>


        </div>
        <div style="display: flex">
          <el-form-item label="团购价" style="width: 185px" prop="price" :rules="{ required: true, message: '请输入团购价', trigger: 'blur' }">
            <el-input v-model="form.price" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label-width="150px" class="foregroundDisplay" label="是否在前台显示" style="width: 185px"  prop="isShow">
            <el-checkbox  v-model="form.isShow" size="medium"></el-checkbox>
          </el-form-item>

        </div>
        <el-tabs>
          <el-tab-pane label="SKU">
            <el-row style="display: flex;  position: relative;margin-left: 90px">
              <span class="el-icon-plus" style="position: absolute; top: 69px;left: -25px; color: #409EFF;"
                    @click="addProduct"/>
              <el-col :span="16">
                <el-table
                  :data="productList"
                  border
                  stripe
                  style="width: 100%;"
                >
                  <el-table-column
                    label="商品名称"
                    min-width="320"
                  >
                    <template slot-scope="scope">
                      <el-select style="width: 100%" value-key="id" v-model="scope.row.name" filterable placeholder="请选择"
                                 @focus="selectIndex(scope)"      @change="selectClick(scope)" :filter-method="productMethod" >
                        <el-option
                          v-for="(item,index) in listForm"
                          :key="item.id"
                          :label="item.name"
                          :value="item"
                        >
                        </el-option>
                        <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                          <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                          <div class="elOption" @click="toAddProduct">搜索商品</div>
                          <div class="elOption1" @click="toSearchProduct">新增商品</div>
                        </div>
                        <div style="height: 30px"></div>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="商品图片"
                    width="80"
                    align="center"
                    prop="thumbnail"
                  >
                    <template slot-scope="{row}">
                      <img :src="row.thumbnail" v-if="row.thumbnail!=''" style="width: 50px;height: 50px">
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="规格"
                    min-width="220"
                  >
                    <template slot-scope="{row}">
                      <span>{{row.spec}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位"
                    width="120"
                  >
                    <template slot-scope="{row}">
                      <span>{{row.unit}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template v-if="!row.isList" slot-scope="{row}">
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <a @click="delProduct(row)">
                          <i style="color: #F56C6C" class="el-icon-delete"/>
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="editProduct('productForm')">
            &nbsp&nbsp完 成&nbsp&nbsp
          </el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-dialog
      title="新增商品"
      :visible.sync="procuctVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="productClose">
      <div style="height: 65vh;overflow: auto;position: relative;">
        <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
      </div>
    </el-dialog>
    <el-dialog
      title="搜索商品"
      :visible.sync="orderVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="orderClose">
      <div style="position: relative;">
        <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '@/components/ProductList/productList'
  import MultiUpload from '@/components/Upload/multiUpload'
  import VideoUpload from '@/components/Upload/videoUpload'
  import Tinymce from '@/components/Tinymce'
  import { EventBus } from '@/api/eventBus'
  import SingleUpload from '@/components/Upload/singleUpload'
  import { list } from '@/api/product'
  import {find,update} from '@/api/groupBuy'
  import permission from '@/directive/permission'
  import { list as distributionList } from '@/api/distribution.js'

  export default {
    name: 'sevengroupBuy-edit',
    directives: {elDragDialog,permission},
    data(){
      return{
        disOptions:[],
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        form: {
          id:'',
          type: 2,
          thumbnail:'',
          robotNum:0,
          subTitle:'',
          duration:0,
          endDate: [],
          point:0,
          name:'',
          beginDate:'',
          groupNum:0,
          periodNum:'',
          orderNum:0,
          price:'',
          marketPrice:0,
          isShow:'',
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() + 86400000 < Date.now()
          }
        },
        article: {
          productMeta: {
            images: [],
            video: '',
            label: ''
          },
          content: ''
        },
        index:'',
        orderVisible:false,
        productType: 'order',
        procuctVisible:false,
        clicked: false,
        listForm:[],
        productList:[{
          name:'',
          productId:'',
          quantity:1,
          spec:'',
          thumbnail:'',
          unit:''
        }],
      }
    },
    watch:{ // 路由地址不变的情况下,如果id变化则重新获取数据
      $route (newVal, oldVal) {
        console.log(newVal.query.id);
        console.log( this.form.id)
        if (newVal.name=='sevengroupBuy-edit' && newVal.query.id!=this.form.id) {
          console.log('4444444444444444');
          this.getData()
        }
      }
    },
    created() {

      this.getData()
      this.loadProduct('')
      this.queryDistribution('')
    },
    components: { productAdd, productTable,MultiUpload, VideoUpload, Tinymce,SingleUpload },
    methods:{
      selectIndex(data){
        this.index=data.$index
      },
      productClose() {
        this.procuctVisible = false;
      },
      toAddProduct(){
        this.orderVisible = true;
      },
      orderClose() {
        this.orderVisible = false;
        this.$refs.productList.cancelClick();
      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.procuctVisible = false;
      },
      doubleClick(val) {
        if (this.productList.length==1&&this.productList[0].name==''){
          this.productList[0].productId=val.id
          this.productList[0].name=val.name
          this.productList[0].quantity=1
          this.productList[0].thumbnail=val.thumbnail
          this.productList[0].spec=val.spec1 + val.spec2
          this.productList[0].unit=val.unit
        }else if (this.productList[this.productList.length-1].name==''){
          this.productList[this.productList.length-1].productId=val.id
          this.productList[this.productList.length-1].name=val.name
          this.productList[this.productList.length-1].quantity=1
          this.productList[this.productList.length-1].thumbnail=val.thumbnail
          this.productList[this.productList.length-1].spec=val.spec1 + val.spec2
          this.productList[this.productList.length-1].unit=val.unit
        }else{
          this.productList[this.index].productId=val.id
          this.productList[this.index].name=val.name
          this.productList[this.index].quantity=1
          this.productList[this.index].thumbnail=val.thumbnail
          this.productList[this.index].spec=val.spec1 + val.spec2
          this.productList[this.index].unit=val.unit
        }
        this.searchSame()
        this.orderVisible=false
        this.setAddClickHeight()
      },
      searchSame(){
        var newList={}
        newList=this.productList[this.productList.length-1]
        if (this.productList.length>1){
          for (var i=0;i<this.productList.length-1;i++){
            if (this.productList[i].productId===newList.productId){

              this.productList[i].quantity=this.productList[i].quantity+1
              this.productList.pop()
            }
          }
        }
        this.productList = this.productList.filter(item => {
          return item.name!=''
        })
      },
      queryDistribution(query) {
        const params = new URLSearchParams()
        params.append('pageNum', 1)
        params.append('pageSize', 50)
        params.append('name', query)
        distributionList(params).then(res => {
          this.disOptions = res.data.data
          console.log(res,'分销')
        }).catch(err => {
          console.log(err)
        })
      },
      addClick(data) {
        var _this = this
        if (this.productList.length==1&&this.productList[0].name==''){
          var list=[]
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            }
            list.push(goodsDetails)
          })
          _this.productList=list
          _this.productList[0].quantity=1
        }else{
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            };
            _this.productList.push(goodsDetails)
          });
        }
        this.orderVisible=false
        this.setAddClickHeight()
        this.searchSame()
      },
      addProduct(){
        var products={
          name:'',
          quantity:1,
          spec:'',
          thumbnail:'',
          unit:''
        }
        this.productList.push(products)
        this.setAddClickHeight()
      },
      selectClick(data){
        console.log(data)
        this.productList[data.$index].spec=data.row.name.spec1
        this.productList[data.$index].productId= data.row.name.id
        this.productList[data.$index].thumbnail=data.row.name.thumbnail
        this.productList[data.$index].unit=data.row.name.unit
        this.productList[data.$index].name=data.row.name.name

      },
      getData(){
        this.form.id=this.$route.query.id;
        this.form.endDate=[]
        find(this.form.id).then(res=>{
          this.form.isShow=res.data.groupBuy.isShow
          this.form.name=res.data.groupBuy.name
          this.form.distributionId=res.data.groupBuy.distributionId
          this.form.type=res.data.groupBuy.type
            this.form.duration=res.data.groupBuy.duration
            this.form.robotNum=res.data.groupBuy.robotNum
            this.form.subTitle=res.data.groupBuy.subTitle
            this.form.periodNum=res.data.groupBuy.periodNum
            this.form.thumbnail=res.data.groupBuy.thumbnail
            this.form.endDate.push(res.data.groupBuy.beginDate)
            this.form.endDate.push(res.data.groupBuy.endDate)
            console.log( this.form.endDate)
            this.form.point=res.data.groupBuy.point
            this.form.groupNum=res.data.groupBuy.groupNum
            this.form.orderNum=res.data.groupBuy.orderNum
            this.form.price=res.data.groupBuy.price
            this.form.marketPrice=res.data.groupBuy.marketPrice
            this.productList=res.data.groupBuy.itemList
            this.article=res.data.groupBuy.article
        })
        this.setAddClickHeight()
      },
      productMethod(query){
        this.loadProduct(query)
      },
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }

        this.setAddClickHeight()
      },
      loadProduct(query){
        var param=new URLSearchParams()
        param.append('name',query)
        list(param).then(res=>{
          this.listForm=res.data.data
        })
      },
      setAddClickHeight() {
        setTimeout(() => {
          // 获取表头的高度
          const tableTopHeight = document.querySelector('.el-table__header-wrapper').offsetHeight
          // 获取一行表格高度
          const tableHeight = document.querySelector('.el-table__row').offsetHeight
          // 获取添加按钮样式
          const addClickStyle = document.querySelector('.el-icon-plus')
          // 获取添加按钮高度
          const addClickHeight = addClickStyle.offsetHeight
          // 设置添加按钮的位置
          const moveHeight = tableTopHeight + ((this.productList.length - 1) * tableHeight) + ((tableHeight - addClickHeight) / 2)
          console.log(tableTopHeight, 'tableTopHeight')
          console.log(tableHeight, 'tableHeight')
          console.log(moveHeight, 'moveHeight')
          addClickStyle.style.top = moveHeight + 'px'
        }, 100)
      },
      editProduct(form){
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            this.clicked=true
            let newDate = this.form.endDate
            if(newDate.length >0){
              this.form.beginDate = newDate[0];
              this.form.endDate = newDate[1]
            }
            this.productList = this.productList.filter(item => {
              return item.name!=''
            })
            var product={
              id:this.form.id,
              distributionId:this.form.distributionId,
              type: this.form.type,
              subTitle:this.form.subTitle,
              endDate:this.form.endDate,
              beginDate:this.form.beginDate,
              periodNum:0,
              robotNum:this.form.robotNum,
              duration:this.form.duration,
              thumbnail:this.form.thumbnail,
              point:this.form.point,
              groupNum:this.form.groupNum,
              status:0,
              name:this.form.name,
              orderNum:this.form.orderNum,
              isShow:this.form.isShow,
              price:this.form.price,
              marketPrice:this.form.marketPrice,
              itemList:this.productList,
              article:{
                productMeta:{},
                content:this.article.content
              },
            }
            product.article.productMeta=this.article.productMeta
            console.log(product)
              update(product).then(res=>{
                this.clicked = false
                EventBus.$emit('sevengroupBuy-edit', res.data)
                this.$store.dispatch('tagsView/delView', this.$route).then(({visitedViews}) => {
                  this.$router.push({
                    path: '/sevengroupBuy/list'
                  })
                })// 关闭当前tab回到列表
              }).catch(error=>{
                this.clicked=false
              })

          }
        })
      },
    }
  }
</script>

<style scoped>

/deep/el-upload-list__item is-success{
  width: 90px;
}
.photo-content{
  width: 100%;
  display: flex;
  align-items: flex-end;
  border-top: 1px #eee solid;
  margin-bottom: 20px;
  margin-top: 10px;
}
/deep/.el-input__inner{
  padding: 0 5px;
}
/deep/.el-upload__tip{
  display: none;
}
/deep/.el-upload-list--picture {
  position: absolute;
  width: 110px;
}
.elOption1{
  background-color: #409EFF;
  color:white ;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 25%;
  height: 40px
}
.elOption{
  background-color: #909399;
  color:white ;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 25%;
  height: 40px
}
/deep/ .el-upload--picture-card{
  width: 50px !important;
  height: 50px !important;
  line-height: 50px !important;
  text-align: center;
}
</style>
